var fs = require('fs')
var path = require('path')
var paths = require('../config/pathConfig.js')
var util = require('../utility/util.js')
var pageConfig = require('../config/pageConfig')
var config = require('../config/config')
var Promise = require('bluebird')

var Active = require('./activeHandler')

var testTopicPath = paths.testTopicPath
var testPracticePath = paths.testPracticePath
var testResultPath = paths.testResultPath
var libFilePath = paths.libFilePath

var aPageCount = pageConfig.aPageCount

var safePathCheck = util.safePathCheck

module.exports = {
  /**
   * 获取练习题目总接口
   * @Author   memory
   * @DateTime 2017-04-08
   * @param    {获取类型：练习题(topic), 答案(result), 用户练习(practice)}
   * @param    {页码}
   * @param    {过滤条件：根据练习题目名称过滤(leavel), 根据用户名过滤(user)}
   * @param    {回调函数}
   */
  findAll: function(type, page, filter, callback) {
    var dirPath = '',
      dirPath = getPath(type);

    safePathCheck(dirPath, function() {

      fs.readdir(dirPath, function(err, files) {
        if (err) {
          console.log('testHandler findAll fail. err = ' + err)
          callback('获取失败')
        } else {
          files = files.filter(function(item) {
              return item.indexOf('DS_Store') == -1
            })
            //  可根据练习题名称和用户id来过滤
          if (filter) {
            if (filter.testId) {
              var patt = new RegExp('^' + filter.testId + '\-')
              files = files.filter(function(file) {
                return patt.test(file)
              })
            } else if (filter.userId) {
              var patt = new RegExp('\-' + filter.userId + '.data$')
              files = files.filter(function(file) {
                return patt.test(file)
              })
            }
          }
          files = files.reverse()

          //  如果没有了数据，返回空
          if (!files.length) {
            callback(null, [])
            return
          }

          var promiseAll = []
          files.map(function(file) {
            promiseAll.push(new Promise(function(resolve, reject) {
              fs.readFile(path.join(dirPath, file), function(err, data) {
                if (err) {
                  console.log('testHandler findAll fail. err = ' + err)
                  reject('获取失败')
                } else {
                  resolve(JSON.parse(data))
                }
              })
            }))
          })
          Promise.all(promiseAll).then(function(resArr) {
            //  按创建时间倒序
            resArr.sort(function(obj1, obj2) {
              return new Date(obj2.createdAt) - new Date(obj1.createdAt)
            });
            //  关键字过滤
            if (filter.keyword) {
              resArr = resArr.filter(function(item) {
                return item.keyword && item.keyword.split(' ').indexOf(filter.keyword) > -1
              })
            }
            //  分页
            resArr = resArr.slice((page - 1) * aPageCount, page * aPageCount)

            callback(null, resArr)
          }).catch(function(err) {
            console.log('testHandler findAll fail. err = ' + err.message)
            callback('获取失败')
          })
        }
      })
    })

  },
  /**
   * 添加习题总接口，包括创建练习题，创建习题答案，用户提交习题
   * @param {string}   type     本习题的类型：新练习题(topic)、练习题答案(result)、用户提交习题(practice
   * )
   * @param {object}   content  习题内容，包括习题名称和主体部分
   * @param {string}   user     用户名，当用户提交习题时才有
   * @param {function} callback 接口回调函数
   */
  insert: function(type, content, userId, callback) {
    var id = content.id
    content.topicId = id
    var testBody = util.createTestDb(content)

    var fileName = (id || testBody.id) + (type == 2 ? '-' + userId : '') + '.data',
      path = getPath(type);


    var data = JSON.stringify(testBody, null, 4)
    safePathCheck(path, function() {

      fs.writeFile(path + fileName, data, function(err) {
        if (err) {
          console.log('testHandler add fail. err = ' + err)
          callback('创建习题失败')
        } else {
          if (type == 2) {
            //  用户提交习题动态
            Active.insert(util.createActiveType1_1(userId, testBody))

            var data = fs.readFileSync(testTopicPath + fileName)
            data = JSON.parse(data)
            data.resultCount += 1
            data = JSON.stringify(data, null, 4)
            fs.writeFile(testTopicPath + fileName, data, function(err) {
              if (err) {
                console.log('testHandler insert fail. err = ' + err)
                callback('操作失败')
              } else {
                callback(null, true)
              }
            })
          } else {
            callback(null, true)
          }
        }
      })
    })
  },
  // findByName: function(filter, callback) {
  //   var path = '',
  //     testName = filter.testName,
  //     type = filter.type,
  //     userId = filter.userId,
  //     fileName = testName + (type == 2 ? '-' + userId : '') + '.data',
  //     path = getPath(type);

  //   safePathCheck(path, fileName, function(exists) {
  //     if (!exists) {
  //       callback(null, null)
  //     } else {
  //       fs.readFile(path + fileName, function(err, data) {
  //         if (err) {
  //           console.log('testHandler findByName fail. err = ' + err)
  //           callback('获取习题失败')
  //         } else {
  //           callback(null, JSON.parse(data))
  //         }
  //       })
  //     }
  //   })

  // },
  findById: function(filter, callback) {
    var id = filter.id,
      type = filter.type,
      fileName = id + (type == 2 ? '-' + filter.userId : '') + '.data',
      path = getPath(type);

    safePathCheck(path, fileName, function(exists) {
      if (!exists) {
        callback(null, null)
      } else {

        fs.readFile(path + fileName, function(err, data) {
          if (err) {
            console.log('testHandler findByName fail. err = ' + err)
            callback('获取习题失败')
          } else {
            callback(null, JSON.parse(data))
          }
        })

        // fs.readdir(path, function (err, files) {
        //   if (err) {
        //     console.log('testHandler findById fail. err = ' + err)
        //     callback('获取数据失败')
        //   } else {
        //     files = files.filter(function(item) {
        //       return item.indexOf('DS_Store') == -1
        //     })
        //     var promiseAll = []
        //     files.forEach(function (fileName) {
        //       promiseAll.push(new Promise(function (resolve, reject) {
        //         fs.readFile(path + fileName, function (err, data) {
        //           if (err) {
        //             console.log('testHandler findById fail. err = ' + err)
        //             reject(err)
        //           } else {
        //             resolve(JSON.parse(data))
        //           }
        //         })
        //       }))
        //     })
        //     Promise.all(promiseAll).then(function (resArr) {
        //       var test = resArr.filter(function (item) {
        //         return item.id == id
        //       })[0]
        //       callback(null, test)
        //     }).catch(function (err) {
        //       callback('获取数据失败')
        //     })
        //   }
        // })

      }
    })

  },
  /**
   * 更新习题内容，并没有查找，起这个名字只是为了仿照mongoose的写法
   * @param  {[object]}   filter   过滤条件
   * @param  {[object]}   body     新习题的内容
   * @param  {Function} callback 回调函数
   */
  findByNameAndUpdate: function(filter, body, callback) {
    var testName = body.name + '.data',
      type = filter.type,
      path = getPath(type);

    body.createdAt = new Date()



    var data = JSON.stringify(body, null, 4)

    fs.writeFile(path + testName, data, function(err, newTest) {
      if (err) {
        console.log('testHandler findByNameAndUpdate fail. err = ' + err)
        callback('更新习题失败')
      } else {
        callback(null, newTest)
      }
    })
  },
  findByIdAndUpdate: function(filter, body, callback) {
    var fileName = (body.topicId || body.id) + '.data',
      type = filter.type,
      path = getPath(type);

    body.createdAt = new Date()

    var data = JSON.stringify(body, null, 4)

    fs.writeFile(path + fileName, data, function(err, newTest) {
      if (err) {
        console.log('testHandler findByNameAndUpdate fail. err = ' + err)
        callback('更新习题失败')
      } else {
        callback(null, newTest)
      }
    })
  },
  remove: function(filter, callback) {
    var type = filter.type,
      fileName = (filter.topicId || filter.id) + (type == 2 ? '-' + filter.userId : '') + '.data',
      path = getPath(type),
      fullPath = path + fileName;

    safePathCheck(path, fileName, function(exists) {
      if (!exists) {
        callback('该习题不存在')
      } else {
        fs.unlink(fullPath, function(err) {
          if (err) {
            console.log('testHandler remove fail. err = ' + err)
            callback('删除习题失败')
          } else {
            callback(null)
          }
        })
      }
    })

  }
}


function getPath(type) {
  var path = 0
  switch (+type) {
    case 1:
      path = testTopicPath
      break;
    case 2:
      path = testPracticePath
      break;
    case 3:
      path = testResultPath
      break;
  }
  return path
}